# from subtitle import mysqldb
import mysqldb
import os
import datetime

# 主要处理剪切任务
# 获取任务列表
def getClipSubTaskList(corpid, userid, page='1', pagesize='12'):
    # 根据设置来判断是否需要重建subtask
    cflag = os.environ.get("CREATE_TABLE")
    if(cflag == 'YES'):
        mysqldb.createClipSubTask()
        os.environ["CREATE_TABLE"] = "NO"
    sql = f"select * from clipsubtask where corpid='{corpid}' and cman={userid} and status != 0 order by id desc"
    list = mysqldb.fetchJsonList("clipsubtask" , sql)
    tlen = len(list)
    i_page = int(page) - 1
    if(i_page < 0):
        i_page = 0

    i_pagesize = int(pagesize)
    sbegin = i_page * i_pagesize
    return list[sbegin:sbegin+i_pagesize], tlen

# 获取任务状态
def getClipSubTaskStatus(corpid, userid, taskid):
    sql = f"select * from clipsubtask where corpid='{corpid}' and cman={userid} and id = {taskid}"
    list = mysqldb.fetchJsonList("clipsubtask" , sql)
    return list

# 设置任务的进度
def setClipSubTaskProcess(uuid, process, status = 1):
    sql = f"update clipsubtask set process={process}, status={status}  where uuid1 = '{uuid}'"
    mysqldb.execUpdate(sql)
    return True

# 设置剪切任务失败状态
def setClipSubTaskFault(id):
    sql = f"update clipsubtask set status=-1 where id = {id}"
    mysqldb.execUpdate(sql)
    return True

def getClipSubTask(corpid, uid, taskid):
    sql = f"select * from clipsubtask where corpid ={corpid} and cman = {uid} and id = {taskid}"
    result = mysqldb.fetchOneBySql(sql)
    return result


# 更新subtitle的截图地址
def updateClipSubThumbnail(uuid, url):
    sql = f"update clipsubtask set thumbnail='{url}', duration={duration} where uuid1 = '{uuid}'"
    result = mysqldb.execUpdate(sql)
    return result

# 更新outurl的访问地址
def updateClipSubOutUrl(uuid, url):
    sql = f"update clipsubtask set outurl='{url}' where uuid1 = '{uuid}'"
    result = mysqldb.execUpdate(sql)
    return result

# 增加新任务
def addClipSubTask(task):

    keys = []
    vals = []
    for key, value in task.items():
        keys.append(key)
        vals.append(value)
    skeys = str(keys).replace('[', '').replace(']', '').replace('\'', '')
    svals = str(vals).replace('[', '').replace(']', '').replace('\'now()\'', 'now()')
    sql = f"insert into clipsubtask({skeys}) values({svals})"
    mysqldb.execUpdate(sql)
    return True

# 删除指定任务
def delClipSubTask(corpid, userid, taskid):
    sql = f"update clipsubtask set status = 0, etime=now() where corpid='{corpid}' and cman={userid} and id = {taskid}"
    mysqldb.execUpdate(sql)
    return True

# 增加任务处理日志
def addClipTaskLog(tuuid, logtext, cman = 0):

    sql = f"insert into subtasklog(tuuid, logtext, cman, ctime, type) values(\"{tuuid}\", \"{logtext}\", {cman}, now(), 1)"
    mysqldb.execUpdate(sql)

def getClipTaskLogs(tuuid):
    sql = f"select * from subtasklog where tuuid = '{tuuid}' and type = 1 order by ctime asc"
    list = mysqldb.fetchJsonList("subtasklog" , sql)
    return list
